package com.tgl

import com.tgl.handler.PongHandler
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.ResponseEntity
import org.springframework.test.context.junit4.SpringRunner
import reactor.core.publisher.Mono
import spock.lang.Specification

@SpringBootTest(classes = PongApplication.class)
class PongHandlerTest extends Specification{


    // 测试响应方法receiveMsg()
    def "test receiveMsg"() {
        // given块
        given: "initial conditions"
        // 设置前置条件或数据
        PongHandler pongHandler = new PongHandler();

        // when块
        when: "action is performed"
        // 执行被测试方法或操作
        Mono<ResponseEntity<String>> result = pongHandler.receiveMsg(parameter)
        // then块
        then: "expected outcome"
        // 验证结果或状态

        // where块
        where:
        parameter     | expected
        "hello"  | "Parameter is incorrect"
        "Hello"  | "World"
    }

    // 测试加锁方法-true
    def "test tryLock"() {
        // given块
        given: "initial conditions"
        // 设置前置条件或数据
        PongHandler pongHandler = new PongHandler();

        when: "action is performed"
        pongHandler.tryLock()

        then:
        noExceptionThrown()
    }

    // 测试加锁方法-true
    def "test tryLock2"() {
        // given块
        given: "initial conditions"
        // 设置前置条件或数据
        PongHandler pongHandler = new PongHandler();

        when: "action is performed"

        def threads = (1..4).collect {
            Thread.start {
                pongHandler.receiveMsg("Hello")
                Thread.sleep(5000)
                println "Thread ${it} is running"
            }
        }


        then:
        threads.each { it.join() }

    }
}
